from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse

from config.db_sqlalchemy_config import init_db
from controllers import load_routers
from models.result import Result
from util.inetAddress import InetAddress
# main.py
import holder.audit_listener  # noqa: F401  👈 显式忽略未使用警告

# 生命周期事件
@asynccontextmanager
async def lifespan(_app: FastAPI):
    print("🚀 应用启动，初始化资源...")
    init_db()
    yield
    print("🛑 应用关闭，释放资源...")


app = FastAPI(
    title="模块化路由与动态加载",
    description="本项目演示了如何在 FastAPI 中实现模块化的路由设计。通过自动扫描并加载指定包下的所有路由模块，为每个模块添加唯一的 URL 前缀，从而简化大型项目的管理和扩展。此外，还展示了如何利用 FastAPI 的特性来增强 API 文档的可读性和实用性，以及如何构建一致的错误处理机制和响应格式。",
    version="1.0.0",
    contact={
        "name": "Kevin",
        "url": "https://baidu.com",
        "email": "1944741442@qq.com"
    },
    license_info={
        "name": "Apache 2.0",
        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
    },
    lifespan=lifespan
)


# 自定义异常处理器
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    if exc.status_code == 401:
        return JSONResponse(
            content=Result(success=False, code=exc.status_code, message="Token 无效，请重新登录").dict(),
            status_code=exc.status_code,
            headers=exc.headers
        )
    # 其他 HTTP 异常也统一处理为 Result.error
    return JSONResponse(
        content=Result(success=False, code=exc.status_code, message=exc.detail).dict(),
        status_code=exc.status_code
    )


load_routers(app)  # 加载所有的路由

if __name__ == "__main__":
    app_name = "test-app"  # app名称
    host = InetAddress.get_local_host()  # 获取本地ip
    port = 5000  # 端口
    swagger_path = "/docs"  # Swagger 文档路径
    local_url = f"http://localhost:{port}"
    external_url = f"http://{host}:{port}"
    swagger_url = f"{external_url}{swagger_path}"
    print("-" * 55)
    print(f"\tApplication {app_name} is running! Access URLs:\t")
    print(f"\tLocal: \t\t\t{local_url}\t")
    print(f"\tExternal: \t\t{external_url}\t")
    print(f"\tSwagger文档: \t{swagger_url}\t")
    print("-" * 55)
    # 启动服务（假设是 FastAPI / Uvicorn）
    uvicorn.run("main:app", host=host, port=port, reload=True)
